`
+
Addition
-
Subtraction
*
Multiplication
/
Division
%
Modulo
+=
Incrementing by a constant
-=
Decrementing by a constant
You can perform these arithmetic operations in bash in a few
ways: using the let command, using the double parentheses syntax
$((expression)), and using the expr command. Let’s
consider an example of each method.
Here we perform a multiplication operation using the let
command:
$ let result="4 * 5"
$ echo $result
20
This command takes a variable name, then performs an
arithmetic calculation to resolve its value. Next, we perform another
multiplication operation using the double parentheses syntax:
$ result=$((5 * 5))
$ echo $result
25
In this case, we perform the calculation within double
parentheses. Lastly, we perform an addition operation using the
expr command:
$ result=$(expr 5 + 505)
$ echo $result
510
The expr command evaluates expressions, which don’t have to
be arithmetic operations; for example, you might use it to calculate
the length of some string. Use man expr to learn more about the
capabilities of expr.
Arrays
Bash allows you to create single-dimension arrays. Arrays are a
collection of elements that are indexed. You can access these
elements using their index numbers, where the first indexed number
starts from zero. In bash scripts, you might use arrays whenever you
Black Hat Bash (Early Access) © 2023 by Dolev Farhi and Nick Aleks